package com.lyj.weblog.admin.service.impl;
import com.lyj.weblog.admin.model.vo.user.FindUserInfoRspVO;
import com.lyj.weblog.admin.model.vo.user.UpdateAdminUserPasswordReqVO;
import com.lyj.weblog.admin.service.AdminUserService;
import com.lyj.weblog.common.domain.mapper.UserMapper;
import com.lyj.weblog.common.enums.ResponseCodeEnum;
import com.lyj.weblog.common.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public Response updatePassword(UpdateAdminUserPasswordReqVO updateAdminUserPasswordReqVO) {
        //拿到用户名密码
        String username=updateAdminUserPasswordReqVO.getUsername();
        String password=updateAdminUserPasswordReqVO.getPassword();
        //加密密码
        String encodePassword=passwordEncoder.encode(password);
        //跟新到数据库
        int count=userMapper.updatePasswordByUsername(username, encodePassword);

        return count==1? Response.success():Response.fail(ResponseCodeEnum.USERNAME_NOT_FOUND);
    }

    /**
     * 获取当前登录用户信息
     * @return
     */
    @Override
    public Response findUserInfo() {
        // 获取存储在 ThreadLocal 中的用户信息
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        final String name = authentication.getName();

        return Response.success(FindUserInfoRspVO.builder().username(name).build());
    }
}
